package com.xl.xlserver.gameServer;

import com.alibaba.fastjson.JSONObject;
import com.xl.xlserver.GameUtilEntity.ScokectMessger;
import com.xl.xlserver.mode.cliect.ClientXYMode;
import com.xl.xlserver.mode.login.InitMode;
import com.xl.xlserver.mode.login.LoginMode;
import com.xl.xlserver.utils.ScoketUntils;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;

public class GameMsgHandler extends ChannelInboundHandlerAdapter {

    /**
     * 定义一个channel组管理所有channel
     * GlobalEventExecutor.INSTANCE 是一个全局事件执行器 是一个单例
     */
    // 全局频道变量，存储所有客户端
    private static ChannelGroup channels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);


    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //channels.add(ctx.channel());
       String addrs=  ScoketUntils.CliectAddress(ctx);
        System.out.println("客户端ip地址：{}"+addrs);
        System.out.println("chenlId"+ctx.channel().id().toString());
        InitMode.getInitMode().addContetion(ctx);
        //获取数据
        String dadaJson = ScoketUntils.readMsg(msg);
        System.out.println("接收客户端数据:" + dadaJson);
        ScokectMessger data =  JSONObject.parseObject(dadaJson,ScokectMessger.class);
        if (data.getModetype() == 1){
            //登录相关
           new LoginMode().codeLogin(data, ctx);
            ctx.flush();
        }else if (data.getModetype() == 2){
         //角色进入 及动作广播
            new ClientXYMode().ClientXYMode(data,ctx);

        }

    }
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("server 读取数据完毕..");
        //ctx.flush();//刷新后才将数据发出到SocketChannel
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
            throws Exception {
        cause.printStackTrace();
    }

    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        channels.add(ctx.channel());
        for (Channel channel : channels) {
            channel.writeAndFlush(ctx.channel().remoteAddress() + "，进来啦\n");
        }
    }

    /**
     * 客户端断开方法
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        System.out.println("移除用户信息");
     LobbyManager.userManager.remove(ctx.name());
     InitMode.getInitMode().removeContetion(ctx);
    }

}
